package com.example.demo.nio;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class CustomAsyncListener implements AsyncListener {
    private Logger LOG= LoggerFactory.getLogger(CustomAsyncListener.class);
    @Override public void onComplete(AsyncEvent asyncEvent) throws IOException {

    }

    @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException {
        AsyncContext asyncContext= asyncEvent.getAsyncContext();
        try{
            ServletRequest req= asyncContext.getRequest();
            String uri= (String) req.getAttribute(Constant.URI);
            Map params= (Map) req.getAttribute(Constant.PARAMS);
            LOG.error("async req timeOut. uri :{},params:{}",uri, JSON.toJSONString(params));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                HttpServletResponse response= (HttpServletResponse) asyncContext.getResponse();
                response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
            }catch (Exception e1){}
            asyncContext.complete();
        }
    }

    @Override public void onError(AsyncEvent asyncEvent) throws IOException {
        AsyncContext asyncContext= asyncEvent.getAsyncContext();
        try{
            ServletRequest req= asyncContext.getRequest();
            String uri= (String) req.getAttribute(Constant.URI);
            Map params= (Map) req.getAttribute(Constant.PARAMS);
            LOG.error("async req error. uri :{},params:{}",uri, JSON.toJSONString(params));
        }catch (Exception e){
            e.printStackTrace();
            try{
                HttpServletResponse response= (HttpServletResponse) asyncContext.getResponse();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }catch (Exception e1){}
        }finally {
            asyncContext.complete();
        }
    }

    @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException {

    }
}
